package com.mrd.modules.shiro;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mrd.modules.system.entity.SysUserEntity;
import com.mrd.modules.system.service.SysUserService;

@Component("customRealm")
public class CustomRealm extends AuthorizingRealm {

  @Autowired
  SysUserService userService;

  // 设置realm的名称
  @Override
  public void setName(String name) {
    super.setName("customRealm");
  }

  // realm的认证方法，从数据库查询用户信息
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {
    String username = (String) token.getPrincipal();
    String password = new String((char[]) token.getCredentials());

    // 查询用户信息
    SysUserEntity userSearch = new SysUserEntity();
    userSearch.setUsername(username);
    SysUserEntity user = userService.queryOneObject(userSearch);

    // 账号不存在
    if (user == null) {
      throw new UnknownAccountException("账号或密码不正确");
    }

    // 密码错误
    if (!password.equals(user.getPassword())) {
      throw new IncorrectCredentialsException("账号或密码不正确");
    }

    /**
     * 设置登录信息，查看session中存的用户信息请通过ShiroUtils.getUserEntity来判断
     */
    // 将activeUser设置simpleAuthenticationInfo
    SimpleAuthenticationInfo simpleAuthenticationInfo =
        new SimpleAuthenticationInfo(user, password, this.getName());

    return simpleAuthenticationInfo;
  }

  // 清除缓存
  public void clearCached() {
    PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
    super.clearCache(principals);
  }

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
    return null;
  }


}
